//
//  SwiftComposeController.swift
//  WeiBoSwift
//
//  Created by Jacky Sun on 16/5/30.
//  Copyright © 2016年 syf. All rights reserved.
//

let fontSize: CGFloat = 20


import UIKit
import SwiftyJSON
import SnapKit
import SVProgressHUD
class SwiftComposeController: UIViewController {

    //MARK: - 懒加载表情键盘
    private lazy var emotion: EmojiKeyBoardController = EmojiKeyBoardController { [unowned self](emotion) in
         self.textView.insertEmotion(emotion, fontSize: fontSize)
    }
    // 懒加载 图片选择器
    private lazy var imgPickerVC: PictureSelectViewController = PictureSelectViewController()
    // 是否需要弹出键盘
    var ISNeedPop: Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        addChildViewController(emotion)
        addChildViewController(imgPickerVC)
        
        //1.初始化导航栏
        setupNav()
        //2、 初始化输入框
        setupInputTextview()
        //3、 设置工具条
        setupToolBar()
        //4、 初始化图片选择器
        setupPhotoSelectView()
        
        //5. 给键盘添加监听
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SwiftComposeController.keyboardFrameChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if !ISNeedPop{
            textView.becomeFirstResponder()
                    }
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }
    
    // 收到的通知
    func keyboardFrameChange(notifi: NSNotification){
        print(notifi.userInfo!)
        
     let dict = notifi.userInfo!
    
    let xxx = dict["UIKeyboardFrameEndUserInfoKey"] as! NSValue
    let rect = xxx.CGRectValue()
   
    let bottomCons = -(UIScreen.mainScreen().bounds.size.height - rect.origin.y)
        self.toolbar.snp_updateConstraints(closure: { (make) in
            make.bottom.equalTo(bottomCons)
        })
        //
        
        // 动画时间
      let animTime = dict["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber
        // 动画节奏
      let curve = dict["UIKeyboardAnimationCurveUserInfoKey"] as! NSNumber
        
        UIView.animateWithDuration(animTime.doubleValue) {
            // 设置动画节奏
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve.integerValue)!)
            self.view.layoutIfNeeded()
        }
    }
    
    
    deinit{
        
        print("滚")
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

 //MAEK: - 初始化导航栏
    private func setupNav(){
        //1、 添加左侧按钮
        let leftbarBtn = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(SwiftComposeController.closeVC))
        navigationItem.leftBarButtonItem = leftbarBtn
        
        //2、 添加右侧按钮
        let rightbarBtn = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: #selector(SwiftComposeController.composeStatus))
        rightbarBtn.enabled = false
        navigationItem.rightBarButtonItem = rightbarBtn
        
        //3 添加中间视图
        let titleLab = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
          titleLab.attributedText =  setupLabAttibuteText()
        titleLab.numberOfLines = 2
        titleLab.textAlignment = .Center
        navigationItem.titleView = titleLab
    }
    
    //MAEK: - 初始化输框
    private func setupInputTextview(){
        view.addSubview(textView)
        textView.addSubview(placeholderLabel)
        placeholderLabel.font = textView.font
        
        textView.frame = view.bounds
        placeholderLabel.snp_makeConstraints { (make) in
            make.left.equalTo(5)
            make.top.equalTo(textView).offset(8)
        }
    }
 
    //MARK: -m 初始化工具条
    private func setupToolBar(){
        view.addSubview(toolbar)
    
        toolbar.snp_makeConstraints { (make) in
         make.left.right.bottom.equalTo(0)
         make.height.equalTo(44)
        }
    }

    //MARK: - 初始化图片选择器
    private func setupPhotoSelectView(){
      //  view.addSubview(imgPickerVC.view)
    
     view.insertSubview(imgPickerVC.view, belowSubview: toolbar)
        imgPickerVC.view.snp_makeConstraints { (make) in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(0)
        }
    }
    
    private func setupLabAttibuteText() ->NSAttributedString {
        
        let str = "发送微博" + "\n" +  UserAccount.getUserAccount()!.screen_name!
        let attriStr  = NSMutableAttributedString(string: str)
        
        attriStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(15), range: NSMakeRange(0, 4))
          attriStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(13), range: NSMakeRange(5, str.characters.count-5))
    
        attriStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSMakeRange(0, 4))
        attriStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSMakeRange(5, str.characters.count-5))
    
        return attriStr
    }
    
    func closeVC(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: 发送微博
    func composeStatus(){
        
       //  print(textView.getLookOverText())
        
        var path = "2/statuses/"
        let params = ["access_token":UserAccount.getUserAccount()!.access_token! , "status": textView.getLookOverText()]
        
       let image = imgPickerVC.pictureArr.first
        if  let img = image {

            path += "upload.json"
            NewWorkRequest.shareNewWorkRequest().POST(path, parameters: params, constructingBodyWithBlock: { (formData) in
                let data = UIImagePNGRepresentation(img)
                 formData.appendPartWithFileData(data!, name: "pic", fileName: "adv.png", mimeType: "")
                
                }, success: { (_, JSON) in
                SVProgressHUD.showSuccessWithStatus("发送成功", maskType: SVProgressHUDMaskType.Black)
                self.closeVC()
                }, failure: { (_, error) in
                SVProgressHUD.showErrorWithStatus("发送失败", maskType: .Black)
            })
        }
        else{
            path += "update.json"

            NewWorkRequest.shareNewWorkRequest().POST(path, parameters: params, success: { (_, result) in
               // print(result)
                let dict = JSON(result!)
                if dict["id"].stringValue.characters.count > 0 {
                    SVProgressHUD.showSuccessWithStatus("发送成功", maskType: SVProgressHUDMaskType.Black)
                    self.closeVC()
                }
            }) { (_, error) in
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败", maskType: .Black)
            }
        }

    }
 
    
    // 选择图片
     func selectPicture(){
        print(#function)
        textView.resignFirstResponder()
        
        ISNeedPop = true
        imgPickerVC.view.snp_updateConstraints { (make) in
            make.height.equalTo(UIScreen.mainScreen().bounds.size.height * 0.6)
        }
    }
    
    // 切换表情键盘
     func inputEmoticon(){
        print(#function)
        
        textView.resignFirstResponder()
        // 如果是系统键盘 ， 那就选表情键盘；反之亦然
        textView.inputView = (textView.inputView == nil) ? emotion.view : nil
        textView.becomeFirstResponder()
    }
    
    
    // MARK: - 懒加载
     lazy var textView: UITextView = {
        let tv = UITextView()
        // 允许竖直方向有弹簧
        tv.alwaysBounceVertical = true
        // 键盘消失的模式
        tv.keyboardDismissMode = .OnDrag
        tv.font = UIFont.systemFontOfSize(fontSize)
        tv.delegate = self
        return tv
    }()
    
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.darkGrayColor()
        label.sizeToFit()
        label.text = "分享新鲜事..."
        return label
    }()
    
    private lazy var toolbar: UIToolbar = {
       let toolbar = UIToolbar()
        let arrs = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
                                         
     ["imageName": "compose_mentionbutton_background"],
     
     ["imageName": "compose_trendbutton_background"],
     
     ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
     
     ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        
       for (index, dict) in arrs.enumerate(){
            let item =  UIBarButtonItem.init(imgStr: dict["imageName"]!, target: self, action: dict["action"])
             items.append(item)
            
            let flexItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            if index != arrs.count - 1{
            items.append(flexItem)
            }
        }
        toolbar.items = items
        return toolbar
    }()
}


extension SwiftComposeController : UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        
        let str = textView.getLookOverText()
        placeholderLabel.hidden =  str.characters.count > 0
        navigationItem.rightBarButtonItem?.enabled = str.characters.count > 0
    }
    
}
